﻿/// 幻灯片播放组件
/// @param {Array,HTMLCollection} 轮换内容
/// @param {Array,HTMLCollection} 控制标签
/// @param {Object} 组件参数
$.Tab = function(contents, tabs, options) {
	var t = this, options = options || { };
	
	for (var i in $.Tab.options) {
	    if (!options[i]) {
	        options[i] = $.Tab.options[i];
	    }
	}
	t.options = options;
	
	t._total = contents.length;
	t._contents = contents;
	t._curSelected = options.curSelected != null ? options.curSelected : -1;

	contents.each(function(el, i) {
		if (i == t._curSelected) {
			$(this).addClass(options.selectedClass);
		} else {
			$(this).removeClass(options.selectedClass);
		}
	});

	if (tabs != null) {
		t._tabs = tabs;
		
		tabs.each(function(el, i) {
			$(this)[i == t._curSelected ? "addClass" : "removeClass"](options.selectedClass);
		});
		
		if (options.selectWhen != null) {
		    if (options.selectWhen === options.unselectWhen) {
		        tabs.each(function(el, i) {
				    $(this).on(options.selectWhen, function(e) {
					    if (t._curSelected == i) {
					        t.select(-1);
					    } else {
					        t.select(i);
					    }
				    });
			    });
		    } else {
			    tabs.each(function(el, i) {
				    $(this).on(options.selectWhen, function() {
					    t.select(i);
				    });
			    });
			    
			    if (options.unselectWhen) {
		            tabs.each(function(el, i) {
				        $(this).on(options.selectWhen, function() {
					        if (t._curSelected == i) {
					            t.select(-1);
					        }
				        });
			        });
		        }
		    }
		}
	}
};

$.extend($.Tab.prototype, {
	/// 选择某个幻灯片
	/// @param {Number,String} 序号或相对值("+n"、"-n")
	select : function(i) {
		var t = this, options = t.options;

		// 给控制标签添加样式类
		t._tabs && t._tabs.each(function(el, j) {
			$(t._tabs[j])[i == j ? "addClass" : "removeClass"](options.selectedClass);
		});

		var newSelected, unselected = $([]), temp;
		t._contents.each(function(el, j) {
			if (i == j) {
				newSelected = this;
			} else {
				unselected.push(this);
			}
		});

		unselected.removeClass(options.selectedClass);
		
		t._finishSelecting(i);
	},
	
	current : function() { return this._curSelected; },

	/// 完成选择操作
	/// @param {Number} 序号
	_finishSelecting : function(i) {
		var t = this;
		if (i != null && t._curSelected != i) {
			var content = t._contents[i], eArgs = [i, t._curSelected];
            
			$(content).addClass(t.options.selectedClass);
			
			// 触发select事件
			t.onSelect && t.onSelect(i, t._curSelected);
			
			t._curSelected = i;
		}
	}
});

$.Tab.options = {
	selectedClass : "current",
	selectWhen : "click"
};